// * TreeNode 组件
<template>
  <ul class="tree-ul">
    <li class="tree-li">
      <span class="tree-expand" v-if="hasChildren" @click="handleExpand">
        <span v-if="hasExpanded">-</span>
        <span v-else>+</span>
      </span>
      <Checkbox
        v-if="showCheckbox"
        :value="data.checked"
        @input="handleCheck"
      />
      <span>{{ data.title }}</span>
      <template v-if="hasChildren && hasExpanded">
        <TreeNode
          v-for="(item, index) in data.children"
          :key="`tree-node-children-${index}`"
          :data="item"
          :show-checkbox="showCheckbox"
        />
      </template>
    </li>
  </ul>
</template>

<script>
import Checkbox from '../Checkbox'
import { findComponentUpward } from '../../utils/assist'

export default {
  name: 'TreeNode',

  components: { Checkbox },

  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
    showCheckbox: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      tree: findComponentUpward(this, 'Tree'),
    }
  },

  computed: {
    hasChildren() {
      return this.data.children && this.data.children.length > 0
    },
    hasExpanded() {
      return this.data.expand
    },
  },

  watch: {
    'data.children': {
      handler(data) {
        if (data) {
          const checkedAll = data.every(item => !!item.checked)
          this.$set(this.data, 'checked', checkedAll)
        }
      },
      deep: true,
    },
  },

  created() {},

  mounted() {},

  methods: {
    handleCheck() {
      this.updateTreeDown(this.data, !this.data.checked)

      if (this.tree) this.tree.emitEvent('on-check-change', this.data)
    },

    updateTreeDown(data, checked) {
      this.$set(data, 'checked', checked)

      if (data.children && data.children.length > 0) {
        data.children.forEach(item => this.updateTreeDown(item, checked))
      }
    },

    handleExpand() {
      const { expand } = this.data
      this.$set(this.data, 'expand', !expand)

      if (this.tree) this.tree.emitEvent('on-toggle-expand', this.data)
    },
  },
}
</script>

<style lang="scss" scoped>
.tree-ul,
.tree-li {
  list-style: none;
  padding-left: 10px;
}
.tree-expand {
  cursor: pointer;
}
</style>
